package concurrentV;

import java.util.LinkedList;
import java.util.Queue;

public class ConsumerProducer {

    private static final int BUFFER_SIZE = 5;

    private   Object lock = new Object();

    private Queue<Integer> bufferArr = new LinkedList<>();

    private void producer() {
        for (int i = 0; i < 100; i++) {
            synchronized (lock) {
                if (bufferArr.size() == BUFFER_SIZE) {
                    try {
                        System.out.println("生产者队列已满，阻塞线程，等待消费者消费....");
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("生产元素: " +  i );
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                bufferArr.offer(i);
                lock.notifyAll();
            }
        }

    }

    private void consumer() {
        while (true){
            synchronized (lock) {
                if(bufferArr.size() == 0){
                    System.out.println("队列为空，消费者阻塞...");
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("消费元素：" + bufferArr.poll());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.notifyAll();
            }
        }

    }

    public static void main(String[] args) {
        ConsumerProducer consumerProducer = new ConsumerProducer();
        new Thread(() -> consumerProducer.producer(),"生产").start();
        new Thread(() -> consumerProducer.consumer(),"消费").start();
    }

}
